export const parseTime = (time, pattern) => {
  if (arguments.length === 0 || !time) {
	return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
	date = time
  } else {
	if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
	  time = parseInt(time)
	} else if (typeof time === 'string') {
	  time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
	}
	if ((typeof time === 'number') && (time.toString().length === 10)) {
	  time = time * 1000
	}
	date = new Date(time)
  }
  const formatObj = {
	y: date.getFullYear(),
	m: date.getMonth() + 1,
	d: date.getDate(),
	h: date.getHours(),
	i: date.getMinutes(),
	s: date.getSeconds(),
	a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
	let value = formatObj[key]
	// Note: getDay() returns 0 on Sunday
	if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
	if (result.length > 0 && value < 10) {
	  value = '0' + value
	}
	return value || 0
  })
  return time_str
}
	
export const getQueryString = (name) =>{
	const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`);
	const r = window.location.search.substr(1).match(reg);
	if (r != null) return unescape(r[2]);
	return null;
}

export const downloadFile = (url, params = {}, withToken = true, needBaseUrl = true) =>{
	const token = this.getCookie('X-Access-Token');
	const headers = withToken ? {
		'X-Access-Token': token
	} : {};
	url = needBaseUrl ? `${baseUrl}${url}` : url;
	return axios({
		url,
		method: 'GET',
		params,
		responseType: 'blob',
		headers
	});
}
	
export const downloadBlobFile = (blob, filename)=> {
	const objUrl = window.URL.createObjectURL(blob);
	const a = document.createElement('a');
	if ('download' in a) {
		document.body.appendChild(a);
		a.style.display = 'none';
		a.href = objUrl;
		a.download = filename;
		a.click();
		window.URL.revokeObjectURL(objUrl);
		document.body.removeChild(a);
		return;
	}
	// IE
	navigator.msSaveBlob(blob, filename);
}

//获取当前年份和月份
export const doHandleDate = () => {
	var myDate = new Date();
	var tYear = myDate.getFullYear();
	var tMonth = myDate.getMonth();
	var m = tMonth + 1;
	if (m.toString().length == 1) {
		m = "0" + m;
	}
	return tYear + '-' + m;
}

// 邮箱校验
export const regEmail = (val) => {
	const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
	return (reg.test(val))
}

// //获取当前时区
export const getTimeZone = () => {
    var offset = new Date().getTimezoneOffset();
    var sign = offset < 0? "" : "-";
    var hours = Math.abs(Math.floor(offset / 60));
    return Number(sign + hours); //+ ":" + ("0" + minutes).slice(-2);
}

//转为百分比，并保留两位小数
export const calculatePercentage = (partialValue, totalValue) => {
    if (totalValue === 0 || isNaN(partialValue) || isNaN(totalValue)) {
        return '0%'; // 防止除以0或非数字输入
    }
    const percentage = (partialValue / totalValue) * 100;
    return `${percentage.toFixed(2)}%`; // 保留两位小数
}

export const removeMinusSign = (num) => {
	const numStr = String(num);
	if(numStr.slice(0,1) == "-" || numStr.slice(0,1) == "+"){
		return numStr.slice(0,1) + "$" + numStr.slice(1);
	}
    else{
		return "$" + num;
	}
}

//四舍五入保留n位小数，和toFixed区别在于，当为整数时，不会自动后面加上小数点和0
export const roundToDecimal = (num,n) => {
	const square = Math.pow(10, n || 2);
	return Math.round(num * square) / square;
}

// fixNum:保留的小数位数
//小数转为百分比，并四舍五入保留几位小数
export const toFixPercent = (num = 0,fixNum = 2) =>{
  let num1 = Number(num)*100 || 0;
  let fixNum1 = Math.pow(10,Number(fixNum));
  return Math.round(num1*fixNum1)/fixNum1+'%';
}
